package com.rustic.server.controller.api;

import cn.hutool.core.collection.CollUtil;
import cn.xy.base.server.bean.IPage;
import cn.xy.base.server.utils.PageUtil;
import cn.xy.commons.annotation.ApiAuth;
import com.rustic.server.enums.LinkType;
import com.rustic.server.po.Rustic;
import com.rustic.server.query.RusticUserListQuery;
import com.rustic.server.service.CommentService;
import com.rustic.server.service.RusticService;
import com.rustic.server.vo.RusticWebVO;
import com.rustic.server.vo.list.RusticWebListVO;
import com.rustic.server.vo.RusticVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rustic.server.web.WebContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import cn.xy.commons.core.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 表[rustic]对应的前台接口
 *
 * @author auto
 */

@Slf4j
@RestController
@RequestMapping("/api/rustic")
@Api(tags = {"乡村接口"})
@ApiAuth(ignore = true)
public class RusticController {

    @Autowired
    private RusticService rusticService;

    @Autowired
    private CommentService commentService;

    @ApiOperation(value = "乡村-列表")
    @GetMapping("/list")
    public Result<Page<RusticWebListVO>> list(RusticUserListQuery query) {
        int userId = WebContext.getUserId();
        //FIXME 根据需要修改搜索条件
        LambdaQueryWrapper<Rustic> queryWrapper = rusticService.toUserListWrapper(query);
        Page<Rustic> pageData = rusticService.page(query.toPage(), queryWrapper);
        List<Rustic> rusticList = pageData.getRecords();
        if (CollUtil.isEmpty(rusticList)) {
            return Result.data(new Page<>());
        }
        List<RusticWebListVO> results = rusticService.toWebListVo(rusticList, userId);
        return Result.data(PageUtil.toPage(pageData, results));
    }

    @ApiOperation(value = "乡村-详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "乡村id"),
    })
    @GetMapping("/detail")
    public Result<RusticWebVO> detail(int id) {
        if (id <= 0) {
            return Result.error(RusticService.RUSTIC_NOT_EXIST);
        }
        Rustic rustic = rusticService.getById(id);
        if (rustic == null) {
            return Result.error(RusticService.RUSTIC_NOT_EXIST);
        }
        RusticWebVO rusticVO = new RusticWebVO(rustic);
        int userId = WebContext.getUserId();
        commentService.setInteractionStatus(rusticVO, userId, rustic.getId(), LinkType.RUSTIC);
        return Result.data(rusticVO);
    }

}
